package com.mobile.config;

import com.mobile.constants.Constant;
import com.mobile.tools.PackageDataTools;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SafeGuardAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;

import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class ChatConfig {

    /**
     * 创建并返回一个ChatClient的Spring Bean实例。
     *
     * @param builder 用于构建ChatClient实例的构建者对象
     * @return 构建好的ChatClient实例
     */
    @Bean
    public ChatClient chatClient(ChatClient.Builder builder,
                                 Advisor simpleLoggerAdvisor,
                                 Advisor messageChatMemoryAdvisor,
                                 Advisor safeGuardAdvisor,
                                 PackageDataTools packageDataTools) {
        return builder
                .defaultSystem(Constant.SYSTEM_ROLE) //设置默认的系统角色
                .defaultAdvisors(simpleLoggerAdvisor, messageChatMemoryAdvisor ,safeGuardAdvisor)//设置默认的Advisor
                .defaultTools(packageDataTools)
                .build();
    }

    /**
     * 创建并返回一个SimpleLoggerAdvisor的Spring Bean实例。
     */
    @Bean
    public Advisor simpleLoggerAdvisor() {
        return new SimpleLoggerAdvisor();
    }

    /**
     * 创建并返回聊天记忆管理器的Spring Bean(基于内存实现)
     */
    @Bean
    public ChatMemory chatMemory(){
        return new InMemoryChatMemory();
    }

    /**
     * 创建并返回聊天记忆管理advisor的Spring Bean
     *
     * @param chatMemory 聊天记忆管理器实例
     * @return MessageChatMemoryAdvisor 实例，用于在聊天过程中维护上下文
     */
    @Bean
    public Advisor messageChatMemoryAdvisor(ChatMemory chatMemory) {
        return new MessageChatMemoryAdvisor(chatMemory);
    }

    /**
     * 过滤敏感词
     */
    @Bean
    public Advisor safeGuardAdvisor(){
        // 敏感词列表（示例数据，建议实际使用时从配置文件或数据库读取）
        List<String> sensitiveWords = List.of("sb", "傻逼");
        // 创建安全防护Advisor，参数依次为：敏感词库、违规提示语、advisor处理优先级，数字越小越优先
        return new SafeGuardAdvisor(
                sensitiveWords,
                "敏感词提示：请勿输入敏感词！",
                Advisor.DEFAULT_CHAT_MEMORY_PRECEDENCE_ORDER
        );
    }

    /**
     * 创建并返回一个VectorStore的Spring Bean实例。
     *
     * @param embeddingModel 向量模型
     */
    @Bean
    public VectorStore vectorStore(EmbeddingModel embeddingModel) {
        return SimpleVectorStore.builder(embeddingModel).build();
    }
}
